import React, { useEffect, useRef } from 'react'
import {
  Button,
  Card,
  Breadcrumb,
  Form,
  Radio,
  Select,
  DatePicker,
  Table,
  Image,
  Space,
  Tag,
  message,
  Modal,
} from 'antd'

import styles from './index.module.scss'
import { Link } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux'
import {
  delArticle,
  getArticleList,
  getChannelList,
} from '@/store/actions/article'
import defaultImg from '@/assets/error.png'
import {
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons'
import { useHistory } from 'react-router-dom'

const { Option } = Select
const { RangePicker } = DatePicker
const { confirm } = Modal

const STATUS = [
  { id: -1, title: '全部', color: 'magenta' },
  { id: 0, title: '草稿', color: 'red' },
  { id: 1, title: '待审核', color: 'volcano' },
  { id: 2, title: '审核通过', color: 'lime' },
  { id: 3, title: '审核失败', color: 'gold' },
]

export default function Article() {
  const channels = useSelector((state) => state.article.channels)
  const articlesObj = useSelector((state) => state.article.articles)
  const dispatch = useDispatch()
  const history = useHistory()
  // console.log(articlesObj)

  useEffect(() => {
    dispatch(getChannelList())
    dispatch(getArticleList())
  }, [dispatch])

  const params = useRef({})
  //筛选
  const onFinish = (values) => {
    console.log(values, 115)
    //1.屏蔽掉 -1 的 status情况
    if (values.state !== -1) {
      params.current.status = values.status
    }
    //2.处理日期，将日期转换成：xxxx-xx-xx xx:xx:xx

    if (values.date) {
      params.current.begin_pubdate = values.date[0]
        .startOf('day')
        .format('YYYY-MM-DD HH:mm:ss')
      params.current.end_pubdate = values.date[1]
        .endOf('day')
        .format('YYYY-MM-DD HH:mm:ss')
    }
    //3.处理频道的选择
    if (values.channel_id) {
      params.current.channel_id = values.channel_id
    }
    dispatch(getArticleList(params.current))
  }

  //分页
  const handleChange = (page, pageSize) => {
    console.log(page, pageSize)
    params.current.page = page
    params.current.per_page = pageSize
    dispatch(getArticleList(params.current))
  }

  //处理删除
  const handleDel = (id) => {
    confirm({
      title: '温馨提示',
      icon: <ExclamationCircleOutlined />,
      content: '你确定要删除文章吗',
      async onOk() {
        // console.log('OK');
        // console.log(id, 888)
        await dispatch(delArticle(id))
        await dispatch(getArticleList(params.current))
        message.success('删除成功')
      },
      onCancel() {
        console.log('Cancel')
      },
    })
  }

  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render: (value) => {
        // console.log(value)
        if (value.type === 0) {
          return <Image width={200} height={150} src={defaultImg}></Image>
        } else {
          return (
            <Image
              width={200}
              height={150}
              src={value.images[0]}
              fallback={defaultImg}
            ></Image>
          )
        }
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (value) => {
        // console.log(value)
        const obj = STATUS.find((item) => item.id === value)
        // console.log(obj)
        return <Tag color={obj.color}> {obj.title}</Tag>
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      dataIndex: 'id',
      render: (id) => {
        return (
          <Space>
            <Button
              onClick={() => history.push(`/home/publish/${id}`)}
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
            ></Button>
            <Button
              type="primary"
              shape="circle"
              icon={<DeleteOutlined />}
              onClick={() => handleDel(id)}
            ></Button>
          </Space>
        )
      },
    },
  ]
  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb>
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>文章列表</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form initialValues={{ status: -1 }} onFinish={onFinish}>
          <Form.Item label="状态" name="status">
            <Radio.Group>
              {STATUS.map((item) => (
                <Radio key={item.id} value={item.id}>
                  {item.title}
                </Radio>
              ))}
            </Radio.Group>
          </Form.Item>
          <Form.Item label="频道" name="channel_id">
            <Select
              placeholder="请选择频道"
              // defaultValue="lucy"
              style={{ width: 120 }}
              // onChange={handleChange}
            >
              {channels.map((item) => (
                <Option key={item.id} value={item.id}>
                  {item.name}
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="日期" name="date">
            <RangePicker></RangePicker>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
      </Card>

      <Card
        style={{ marginTop: 30 }}
        title={`根据筛选条件共查询到${articlesObj.total_count}条结果:`}
      >
        <Table
          pagination={{
            position: ['bottomLeft'],
            current: articlesObj.page,
            pageSize: articlesObj.per_page,
            total: articlesObj.total_count,
            onChange: handleChange,
          }}
          dataSource={articlesObj.results}
          columns={columns}
          rowKey="id"
        />
      </Card>
    </div>
  )
}
